package yartiss.engine.simulation.io;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import yartiss.engine.simulation.Event;
import yartiss.engine.simulation.SimulationParameters;
import yartiss.engine.simulation.system.ITask;

public class SimulationWriter {
	
	private BufferedWriter logWriter;
	private Map<ITask, Integer> taksIds = new HashMap<ITask, Integer>();
	
	public void open(String file){
		try {
			if(logWriter != null)
				logWriter.close();
			taksIds.clear();
			logWriter = new BufferedWriter(new FileWriter(file));
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void writeParameters(SimulationParameters parameters){
		try {
			DefaultParamsParser.write(parameters, logWriter);
			int id = 1;
			for (ITask task : parameters.getTaskSet()) {
				taksIds.put(task, id);
				id++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void writeEvent(Event event){
		try {
			logWriter.write(event.getDate() +"\t"+event.getMetric(Event.EnergyLevel)+"\tt"+ taksIds.get(event.getTask())+"\t"+event+"\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void close(){
		try {
			if(logWriter != null)
				logWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
